package com.demo;

import java.io.File;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**读取索引文件，term属于多个doc
 * @author Ziroom
 *
 */
public class Demo7 {

	private static final String PATH = "d:\\zsl\\index3";

	public static void createIndex() throws Exception {
        //1、创建一个Director对象，指定索引库保存的位置。

        //1.1把索引库保存在内存中
        //Directory directory = new RAMDirectory();

        //1.2把索引库保存在磁盘
        Directory directory = FSDirectory.open(new File(PATH).toPath());

        //2、基于Directory对象创建一个IndexWriter对象
        IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        //当使用IKAnalyzer分词时，是如下写法。
       	//IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        IndexWriter indexWriter = new IndexWriter(directory, config);

        //3、读取磁盘上的文件，对应每个文件创建一个文档对象。
        /*String[] arr = new String[] {
        	"ail ailment action aim aimless air airborne airconditioning aircraft alight",
        	"action aircrew airdrome airfield airlift albany albino album albumen alice alienation",
        	"allergic allergy boy book bus best big buy busy bad baeutiful big bought"
        };*/
        String[] arr = new String[] {
        	// "abc acc acd acea aceb acee acef",
        	"abc abcda abcdb abcdc abcdd abct abctm abcui abcuu abcy abe abec abeft abefz abfa",
        	"abft abfta abftb abftc abftd abfte abftf abftg abfth abfti abfz",
        	"acda acdb acdc abctm",
        	"qmq abctm",
        	"zoo abcui abcuu abctm",
        	"mvp abftc abctm",
        	"abctm abctm cqq",
        	"abctm ztt",
        	"avf abctm abcdb abcdc abcdd abct"
        };

        int i=0;
        // abc abcd abcde abced abcqq abct abctm abcui abcuu abcy一起处理block，其中abc abcd abcde一个floor block，剩下的一个floor block
        // abe abec abeft abefz生成一个block
        // for (int j=0; j<800; j++) {
        	for (String str : arr) {
	            //取文件名
	            String fileName = "测试文件" + i++;
	            //文件的内容
	            String fileContent = str;

	            //创建Field
	            //参数1：域的名称，参数2：域的内容，参数3：是否存储
	            Field fieldName = new StringField("name", fileName, Field.Store.YES);
	            Field fieldContent = new TextField("content", fileContent, Field.Store.YES);

	            //创建文档对象
	            Document document = new Document();
	            //向文档对象中添加域
	            document.add(fieldName);
	            document.add(fieldContent);

	            //5、把文档对象写入索引库
	            System.out.println(indexWriter.addDocument(document));
	        }
        //6、关闭indexwriter对象
        indexWriter.close();
    }

	public static void searchIndex() throws Exception {
        //1、创建一个Director对象，指定索引库的位置
        Directory directory = FSDirectory.open(new File(PATH).toPath());
        //2、创建一个IndexReader对象
        IndexReader indexReader = DirectoryReader.open(directory);
        //3、创建一个IndexSearcher对象，构造方法中的参数indexReader对象。
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        //4、创建一个Query对象，TermQuery
        Query query = new TermQuery(new Term("content", "abctm"));
        //5、执行查询，得到一个TopDocs对象
        //参数1：查询对象 参数2：查询结果返回的最大记录数
        TopDocs topDocs = indexSearcher.search(query, 50);
        //6、取查询结果的总记录数
        System.out.println("查询总记录数：" + topDocs.totalHits);
        //7、取文档列表
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        //8、打印文档中的内容
        for (ScoreDoc doc : scoreDocs) {
            //取文档id
            int docId = doc.doc;
            //根据id取文档对象
            Document document = indexSearcher.doc(docId);
            System.out.println(docId);
            System.out.println(document.get("name"));
            System.out.println(document.get("content"));

        }
        //9、关闭IndexReader对象
        indexReader.close();
    }

	public static void main(String[] args) throws Exception {
		//createIndex();
		searchIndex();
	}

}
